package com.joney.website.interceptor;

import com.joney.common.annotation.Auth;
import com.joney.common.pojo.UserSession;
import com.joney.common.utils.CookieUtil;
import com.joney.common.utils.JwtToken;
import com.joney.website.constant.Constants;
import lombok.extern.log4j.Log4j2;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author wangxianchen
 * @create 2018-02-08
 * @desc 权限验证拦截
 */
@Log4j2
public class AuthInterceptor extends HandlerInterceptorAdapter {

    //@Autowired
   // private UserRoleService userRoleService;

    //白名单集合
    private static final Set<String> whiteList = new HashSet<>();

    static{
        whiteList.add("/");
        whiteList.add("/note/login");
        whiteList.add("/note/login_do");
        whiteList.add("/note/register");
        whiteList.add("/note/register_do");
        whiteList.add("/403");
        whiteList.add("/404");
        whiteList.add("/enc");
        whiteList.add("/dec");
        whiteList.add("/blank");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        int status = response.getStatus();
        log.info("-----> header={},url={}",getHeaders(request),url);

        if(whiteList.contains(url)){
            return true;
        }
        if(status==404){
            response.sendRedirect("/404");
            return false;
        }

        //String token = request.getHeader(Constants.HEADER_KEY_TOKEN);
        String token = CookieUtil.getTokenByCookie(request);
        if(token == null){
            log.warn("token is null, the page will be send redirect to '/note/login'");
            response.sendRedirect("/note/login");
            return false;
        }
        if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
            Auth auth = ((HandlerMethod) handler).getMethodAnnotation(Auth.class);
            if(auth != null){

            //}
            //没有声明需要权限,或者声明不验证权限
            //if(auth == null || StringUtils.isEmpty(auth.value())){
            //    return true;
            //}else{
                UserSession session = JwtToken.unsign(token);
                if(session == null){
                    //返回到登录界面
                    response.sendRedirect("/note/login");
                    return false;
                }
/*                CacheManager manager = CacheManager.getInstance();
                Cache tokenCache = manager.getCache(Constants.CACHE_KEY_OF_USER_TOKEN);
                if(tokenCache.get(token) == null){
                    //token失效，返回到指定页面跳转
                    //response.sendRedirect("/token_invalid");
                    response.sendRedirect("/blank");
                    return false;
                }*/

                //在这里实现自己的权限验证逻辑
/*                if(userRoleService.checkPermission(session.getUid(),auth.value())){
                    return true;
                }else{
                    response.sendRedirect("/403");
                    logger.info("没有权限 userID="+session.getUid()+" url="+url);
                    return false;
                }*/
            }
        }

        return true;
    }

    private Map<String,String> getHeaders(HttpServletRequest request){
        Enumeration<String> names = request.getHeaderNames();
        Map<String,String> headerMap = new HashMap<>();
        while(names.hasMoreElements()){
            String name = names.nextElement();
            headerMap.put(name,request.getHeader(name));
        }
        return headerMap;
    }
}
